(in-package :lilu-x11)

(defun get-x11-active-window-id ()
  (let ((trim-cmd "xprop -root | grep '_NET_ACTIVE_WINDOW(WINDOW)' | awk -F ' ' '{print $5}' | tr ',' ' '"))
    (values (parse-integer (subseq
                            (string-trim '(#\Space #\Tab #\Newline)
                                         (uiop:run-program trim-cmd :output :string))
                            2)
                           :radix 16))))

(defun get-x11-window-id-under-pointer ()
  (let ((cmd "xdotool getmouselocation --shell | grep WINDOW | awk -F \"=\" '{print $2}'"))
    (values (parse-integer
             (string-trim '(#\Space #\Tab #\Newline)
                          (uiop:run-program cmd :output :string))))))

(defun take-x11-window-screenshot (pathname &key (window-id
                                                  (get-x11-active-window-id)))
  (let ((import-cmd (format nil "import -window 0x~A ~A" (write-to-string window-id :base 16)
                            (namestring pathname))))
    (format *debug-io* "==> ~A~%" import-cmd)
    (uiop:run-program import-cmd)))
